<template>
  <div class="report-list-wrap">
    <div class="top-wrap box-shadow bg-white">
      <el-button type="primary" plain @click="router.push('/report/add')">添加研报</el-button>
      <el-button type="primary" class="select-item" @click="handlePublishReport">发布研报</el-button>
      <el-date-picker
        v-model="timeRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="YYYY-MM-DD"
        @change="handleSelectChange"
        class="select-item"
      >
      </el-date-picker>
      <el-select 
        filterable 
        v-model="frequencyVal" 
        placeholder="更新频度筛选" 
        clearable 
        class="select-item" 
        style="width:150px"
        @change="handleSelectChange"
      >
        <el-option 
          v-for="item in frequencyOpts" 
          :key="item.value" 
          :label="item.label" 
          :value="item.value">
        </el-option>
      </el-select>
      <el-cascader
        v-model="classifyVal"
        :options="classifyOpts"
        :props="{value:'ClassifyName',label:'ClassifyName',children:'Child',checkStrictly: true}"
        clearable
        placeholder="类型筛选"
        @change="handleSelectChange"
        class="select-item">
      </el-cascader>
      <el-select 
        filterable 
        v-model="statusVal" 
        placeholder="状态筛选" 
        clearable 
        class="select-item" 
        style="width:150px"
        @change="handleSelectChange"
      >
        <el-option 
          v-for="item in statusOpts" 
          :key="item.value" 
          :label="item.label" 
          :value="item.value">
        </el-option>
      </el-select>
      <el-input
        v-model="searchVal"
        placeholder="标题/作者"
        prefix-icon="el-icon-search"
        style="width:250px"
        class="select-item"
        v-search-throttle="handleSelectChange"
        @clear="handleSelectChange"
        clearable
      />
    </div>
    <div class="content-wrap box-shadow bg-white clear-float">
      <el-table
        v-loading="loading"
        :data="tableData"
        @selection-change="handleSelectReport"
        border
        height="65vh"
        :header-cell-style="{background:'#f5f7fa'}"
      >
        <el-table-column type="selection" :selectable="handleRowSelect" width="50" align="center" />
        <el-table-column label="报告标题" align="center">
          <template #default="scope">
            <span class="title">{{ scope.row.Title }}</span>
            <span class="title" v-if="scope.row.CreateTime">({{handleTitleNum(scope.row.CreateTime)}})</span>
          </template>
        </el-table-column>
        <el-table-column label="报告类型" align="center">
          <template #default="scope">
            {{scope.row.ClassifyNameFirst}} / {{scope.row.ClassifyNameSecond}}
          </template>
        </el-table-column>
        <el-table-column label="发布状态" align="center" width="80">
          <template #default="scope">
            <span v-if="scope.row.State===1">未发布</span>
            <span v-if="scope.row.State===2" style="color:#46C371;">已发布</span>
          </template>
        </el-table-column>
        <el-table-column label="发布时间" align="center" width="170">
          <template #default="scope">{{formatTime(scope.row.PublishTime)}}</template>
        </el-table-column>
        <el-table-column label="更新时间" align="center" width="170">
          <template #default="scope">{{formatTime(scope.row.ModifyTime)}}</template>
        </el-table-column>
        <el-table-column label="期数" align="center" width="100">
          <template #default="scope">第{{scope.row.Stage}}期</template>
        </el-table-column>
        <el-table-column property="Frequency" label="频度" align="center" width="80" />
        <el-table-column label="音频" align="center" width="80">
          <template #default="scope">
            <span v-if="!scope.row.VideoUrl" style="color:#46C371;cursor: pointer;">上传</span>
            <span v-else class="title">下载</span>
          </template>
        </el-table-column>
        <el-table-column align="center" width="150">
          <template #header>
            <span style="margin-right:10px">PV / UV</span>
            <el-tooltip placement="top">
              <template #content>
                <p>pv：报告被打开的次数，每次打开都计算一次（只统计有权限用户）</p>
                <p>uv：访问报告的人数，每篇报告同一个人访问只计算一次（只统计有权限用户）</p>
              </template>
              <el-icon>
                <info-filled/>
              </el-icon>
            </el-tooltip>
          </template>
          <template #default="scope">{{scope.row.Pv}} / {{scope.row.Uv}}</template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="160">
          <template #default="scope">
            <template v-if="scope.row.State===1">
              <span style="margin-right:20px;" class="opt-btn-edit">编辑</span>
              <span class="opt-btn-del" @click="handleReportDelete(scope.row.Id)">删除</span>
            </template>
            <template v-if="scope.row.State===2">
              <span style="margin-right:10px" class="opt-btn-del" @click="handleCancelPublishReport(scope.row.Id)">取消发布</span>
              <span v-if="scope.row.MsgIsSend===0" class="opt-btn-edit" @click="handleReportSendMsg(scope.row.Id)">推送消息</span>
              <span v-else class="opt-btn-del" style="cursor: default;">已推送消息</span>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        layout="total,prev, pager, next"
        v-model:currentPage="page"
        :current-page="page"
        @current-change="handlePageChange"
        :page-size="pageSize"
        :total="total"
        style="float: right; margin-top: 20px"
      ></el-pagination>
    </div>
  </div>
</template>
<script lang="ts">
import { defineComponent,reactive, toRefs,ref,computed} from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage ,ElMessageBox} from 'element-plus'
import {apiClassifyList} from '@/api/classify'
import {
  apiReportList,
  apiReportPublish,
  apiReportDelete,
  apiReportCancelPublish,
  apiReportSendMsg
} from '@/api/report'

export default defineComponent({
  setup() {
    const router=new useRouter()

    let filterData=reactive({
      frequencyVal:'',//频度值
      frequencyOpts:[
        {label:'年度',value:'年度'},
        {label:'半年度',value:'半年度'},
        {label:'季度',value:'季度'},
        {label:'月度',value:'月度'},
        {label:'周度',value:'周度'},
        {label:'日度',value:'日度'},
        {label:'不定时',value:'不定时'},
      ],//频度筛选项
      classifyOpts:[],//类型筛选项
      classifyVal:[],//类型值
      statusOpts:[
        {label:'已发布',value:2},
        {label:'未发布',value:1}
      ],// 状态选项
      statusVal:'',
      searchVal:'',//搜索值
      timeRange:[],//选择时间段
      page:1,
      pageSize:20,
      total:0,
      loading:false
    })
    //获取分类数据
    const getClassifyList=async ()=>{
      const res=await apiClassifyList({PageSize:1000,CurrentIndex:0})
      if(res.Ret===200){
        filterData.classifyOpts=res.Data.List||[]
      }
    }
    getClassifyList()

    // 获取研报列表
    let tableData=ref([])
    const keyArr:string[]=[
        'Id',
        'Title',
        'ClassifyNameFirst',
        'ClassifyNameSecond',
        'State',
        'PublishTime',
        'ModifyTime',
        'CreateTime',
        'Stage',
        'Frequency',
        'VideoUrl',
        'VideoName',
        'Pv',
        'Uv',
        'MsgIsSend',
        'ReportCode'
    ] //列表需要的字段key
    const getReportList=async ()=>{
      filterData.loading=true
      const res=await apiReportList({
        PageSize:filterData.pageSize,
        CurrentIndex:filterData.page,
        StartDate:filterData.timeRange?filterData.timeRange[0]:'',
        EndDate:filterData.timeRange?filterData.timeRange[1]:'',
        Frequency:filterData.frequencyVal,
        ClassifyNameFirst:filterData.classifyVal?filterData.classifyVal[0]:'',
        ClassifyNameSecond:filterData.classifyVal?filterData.classifyVal[1]:'',
        State:filterData.statusVal,
        KeyWord:filterData.searchVal
      })
      filterData.loading=false
      if(res.Ret===200){
        // 过滤出需要的字段
        let arr=res.Data.List||[]
        tableData.value=arr.map(item=>{
          let obj={}
          keyArr.forEach(key=>{
            obj[key]=item[key]
          })
          return obj
        })
        filterData.total=res.Data.Paging.Totals
      }
    }
    getReportList()

    // 页面跳转
    const handlePageChange=()=>{
      getReportList()
    }

    // 是否该行可选
    const handleRowSelect=(row)=>{
      if(row.State===2){
        return false
      }else{
        return true
      }
    }

    // 处理表格标题
    const handleTitleNum=(e:string):string=>{
      return `${e.substring(5,7)}${e.substring(8,10)}`
    }

    // 选项/搜索改变 刷新列表
    const handleSelectChange = () => {
      filterData.page=1
      getReportList()
    }

    let selectReportIds:number=[] //选中的报告id集合
    //选择报告
    const handleSelectReport=(e)=>{
      selectReportIds=e.map(item=>{
        return item.Id
      })
    }
    // 发布报告
    const handlePublishReport=async ()=>{
      if(selectReportIds.length===0){
        ElMessage({
          message: '请选择需要发布的报告',
          type: 'warning',
        })
        return
      }
      const res=await apiReportPublish({ReportIds:selectReportIds.join(',')})
      if(res.Ret===200){
        ElMessage({
          message:'发布成功',
          type:"success"
        })
        getReportList()
      }
    }

    // 取消发布报告
    const handleCancelPublishReport=(id:number)=>{
      ElMessageBox.confirm(
        '确认取消吗?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(async ()=>{
        const res=await apiReportCancelPublish({ReportIds:id})
        if(res.Ret===200){
          ElMessage({
            message:"取消成功",
            type:'success'
          })
          getReportList()
        }
      })
    }

    // 删除报告
    const handleReportDelete=(id:number)=>{
      ElMessageBox.confirm(
        '确认删除吗?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(async ()=>{
        const res=await apiReportDelete({ReportIds:id})
        if(res.Ret===200){
          ElMessage({
            message:"删除成功",
            type:'success'
          })
          getReportList()
        }
      })
    }

    // 消息推送
    const handleReportSendMsg=(id:number)=>{
      ElMessageBox.confirm(
        '确认推送吗?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(async ()=>{
        const res=await apiReportSendMsg({ReportIds:id})
        if(res.Ret===200){
          ElMessage({
            message:"推送成功",
            type:'success'
          })
          getReportList()
        }
      })
    }


    return {
      handleSelectChange,
      ...toRefs(filterData),
      tableData,
      handlePageChange,
      handleTitleNum,
      handleRowSelect,
      handlePublishReport,
      handleSelectReport,
      handleReportDelete,
      handleCancelPublishReport,
      handleReportSendMsg,
      router
    }
  }
})
</script>

<style lang="scss" scoped>
.report-list-wrap {
  .top-wrap{
    padding: 20px;
    :deep(.select-item){
      margin-right: 10px;
      margin-bottom: 10px;
    }
  }

  .content-wrap{
    margin-top: 20px;
    padding: 20px;
    .title{
      cursor: pointer;
      color: $textBlue;
    }
    .opt-btn-edit{
      color:$textBlue;
      cursor: pointer;
    }
    .opt-btn-del{
      color:$textRed;
      cursor: pointer;
    }
  }
  
}
</style>
